import pos, { PosAppCustomer, PosGetInCustomer } from 'api/pos';
import { Division, InfoLayout, Toast } from 'components';
import Loading from 'components/loading';
import assets from 'modules/assets';
import { inputIdentityStyle } from 'modules/identity/style';
import React, { Fragment, useEffect, useRef, useState } from 'react';
import { Image, Text, TouchableOpacity, View, ViewStyle, ImageStyle, TextStyle } from 'react-native';
import { ScrollView, TextInput } from 'react-native-gesture-handler';
import ModalDropdown from 'react-native-modal-dropdown';
import { getAuthorization, operate } from 'services/authorization';
import { commonStyle, definedColors, themeColors, translateSize } from 'styles';

import * as styles from './style';

interface IProps {
	style?: ViewStyle
	posGetInCustomerList: PosGetInCustomer[]
	onConfirm: (data: PosGetInCustomer[]) => void,
	onCancel: () => void
}

const ChooseCustomer: React.FC<IProps> = props => {
	const [posGetInCustomerList, setPosGetInCustomerList] = useState<PosGetInCustomer[]>([])
	const [inputType, setInputType] = useState('idcard')
	const [customerList, setCustomerList] = useState<PosAppCustomer[]>([])
	const [currentCustomer, setCurrentCustomer] = useState<PosAppCustomer>({});
	const [noData, setNoData] = useState(false)
	const inputVaule = useRef('')
	const dropdownRef = useRef<ModalDropdown>();

	useEffect(() => {
		setInputType('idcard')
	}, [])

	useEffect(() => {
		setPosGetInCustomerList(props.posGetInCustomerList || [])
	}, [props.posGetInCustomerList]);


	// useEffect(() => {
	// 	inputVaule.current = ''
	// }, [inputType])

	const searchCustomer = () => {
		Loading.show()
		setNoData(false)
		let searchData = inputType === 'idcard' ? { idNumber: inputVaule.current } : { tell: inputVaule.current }
		pos.posApp.getZskFee({
			...searchData,
			...{
				scene: 'szsk',
				projectId: getAuthorization().project.id
			}
		}).then(res => {
			setCustomerList(res.customerList || []);
			if (!res.customerList || res.customerList.length < 1) {
				setNoData(true)
			}
		}).finally(() => { Loading.hide() })
	}
	const renderItem = (item: PosAppCustomer) => {
		return (<View style={itemContainer} key={item.erpId}>
			<Image
				style={itemIcon}
				source={assets.images.icon_customer_male}
			/>
			<View style={itemContent}>
				<InfoLayout title='客户姓名：' titlePartner={<Text style={itemNameFont}>{item.name}</Text>} hideDivier={true} style={itemLayout} />
				<InfoLayout title='身份证号：' titlePartner={<Text style={itemTellFont}>{item.zjNumber}</Text>} hideDivier={true} style={itemLayout} />
				<InfoLayout title='电话号码：' titlePartner={<Text style={itemTellFont}>{item.tel}</Text>} hideDivier={true} style={itemLayout} />
			</View>
			<TouchableOpacity style={itemCheckContainer} onPress={() => {
				operate()
				setCurrentCustomer(item)
			}}>
				<Image
					resizeMode="cover"
					style={itemCheckImage}
					source={item.erpId == currentCustomer.erpId ? assets.images.icon_check : assets.images.icon_uncheck}
				/>
			</TouchableOpacity>
		</View>
		)
	}

	return <View style={[styles.containerCustomer, props.style]}>
		<View style={styles.innerContainer}>
			<View style={styles.itemContainer}>
				<View style={styles.dropdownView}>
					<ModalDropdown
						ref={ref => { dropdownRef.current = ref }}
						dropdownStyle={{ width: '30%' }}
						dropdownTextStyle={{ fontSize: translateSize(32) }}
						options={['身份证号码', '电话号码']}
						onSelect={(index: string, option: string) => {
							setInputType(option === '电话号码' ? 'telphone' : 'idcard')
						}}>
						<TouchableOpacity
							style={{ ...commonStyle.containerRow, ...inputIdentityStyle.typeContainer, marginTop: translateSize(0) }}
							onPress={() => { operate(); dropdownRef.current.show() }}>
							<Text style={inputIdentityStyle.typeContent}>{inputType === 'idcard' ? '身份证' : '手机号'}</Text>
							<Image style={inputIdentityStyle.typeIcon} source={assets.images.icon_arrow_right} />
						</TouchableOpacity>
					</ModalDropdown>
				</View>
				<TextInput
					style={styles.input}
					keyboardType={inputType == 'idcard' ? 'email-address' : 'number-pad'}
					placeholder={inputType == 'idcard' ? '请输入身份证号' : '请输入手机号'}
					onChangeText={text => {
						inputVaule.current = text
					}} />
				<TouchableOpacity onPress={() => {
					operate()
					searchCustomer()
				}}>
					<Text style={[styles.searchBtn, {
						backgroundColor: themeColors.primary
					}]}>搜索</Text>
				</TouchableOpacity>
			</View>
			<ScrollView style={{ flex: 1 }}>
				<View style={styles.content}>
					{noData ? (<Text style={commonStyle.noDataWarn}>未找到客户，请确认用户信息是否正确！</Text>) :
						(<Fragment><ScrollView>
							<View >
								{
									customerList.map(renderItem)
								}
							</View>
						</ScrollView>
						</Fragment>)
					}
				</View>
			</ScrollView>
			<Division />
			<View style={styles.bottomContainer}>
				<TouchableOpacity onPress={() => {
					operate()
					if (!currentCustomer.erpId) {
						Toast.show('请选择客户！')
						return
					}
					if (posGetInCustomerList.find(cusomer => cusomer.erpCustomerId === currentCustomer.erpId)) {
						Toast.show('该客户已经选择，不允许选择相同的客户！')
						return
					}
					posGetInCustomerList.push({ erpCustomerId: currentCustomer.erpId, customerName: currentCustomer.name, zjType: currentCustomer.zjType, zjNumber: currentCustomer.zjNumber, tel: currentCustomer.tel })
					props.onConfirm(posGetInCustomerList)
				}}>
					<Text style={styles.comfirm}>确定</Text>
				</TouchableOpacity>
				<TouchableOpacity onPress={() => {
					operate()
					props.onCancel()
				}}>
					<Text style={styles.cancel}>取消</Text>
				</TouchableOpacity>
			</View>
		</View>
	</View>
}



const container: ViewStyle = {
	backgroundColor: themeColors.pageBg,
	padding: translateSize(32),
	height: '100%'
}


const itemContainer: ViewStyle = {
	width: '100%',
	height: translateSize(215),
	paddingLeft: translateSize(62),
	paddingVertical: translateSize(42),
	paddingRight: translateSize(30),
	flexDirection: 'row',
	alignItems: 'center',
	position: 'relative',
	backgroundColor: definedColors.white,
	borderRadius: translateSize(10),
	marginBottom: translateSize(32)
}

const itemIcon: ImageStyle = {
	width: translateSize(80),
	height: translateSize(80)
}

const itemContent: ImageStyle = {
	flexDirection: 'column',
	justifyContent: 'space-between',
	width: '100%',
	height: '100%'
}

const itemLayout: ViewStyle = {
	paddingTop: translateSize(0),
	paddingBottom: translateSize(0),
	paddingLeft: translateSize(55)
}

const itemTellFont: TextStyle = {
	fontSize: translateSize(24),
	color: definedColors.grayContent
}

const itemNameFont: TextStyle = {
	fontSize: translateSize(28),
	color: definedColors.gray33
}

const itemCheckContainer: ViewStyle = {
	position: 'absolute',
	right: 0,
	top: 0,
	padding: translateSize(28)
}

const itemCheckImage: ImageStyle = {
	width: translateSize(50),
	height: translateSize(50)
}


export default ChooseCustomer

